﻿using System;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using System.Transactions;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using DevExpress.XtraBars;
using THSLib;
using THSERP.BusinessEntities;
namespace THSERP.BaseProvider
{
    partial class BaseModuleERP : BaseModule, IBaseModule
    {
        #region Module handler Functions
#if never
        /// <summary type="Save">
        /// Save customize column of Search Results Control
        /// </summary>
        /// <THSparam name="SearchResultsControlName" type="String"></THSparam>
        public void SaveCustomizeColumnSearchResultsControl(object sender, String strEventName)
        {
            String strSearchResultsControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                sender, strEventName,
                                                "SaveCustomizeColumnSearchResultsControl",
                                                "SearchResultsControlName");
            Control ctrlSearchResults = Controls[strSearchResultsControlName];
            if (ctrlSearchResults != null)
            {
                STGridResultColumnDisplaysController objSTGridResultColumnDisplaysController = new STGridResultColumnDisplaysController();
                objSTGridResultColumnDisplaysController.DeleteGridResultColumnDisplayByModuleName(Name);

                foreach (DevExpress.XtraGrid.Columns.GridColumn GridColumn in ((DevExpress.XtraGrid.Views.Grid.GridView)((DevExpress.XtraGrid.GridControl)ctrlSearchResults).ViewCollection[0]).Columns)
                {
                    if (GridColumn.Visible)
                    {
                        STGridResultColumnDisplaysInfo objSTGridResultColumnDisplaysInfo = new STGridResultColumnDisplaysInfo();
                        objSTGridResultColumnDisplaysInfo.STGridResultColumnName = GridColumn.Name;
                        objSTGridResultColumnDisplaysInfo.STGridResultColumnFieldName = GridColumn.FieldName;
                        objSTGridResultColumnDisplaysInfo.STGridResultColumnCaption = GridColumn.Caption;
                        objSTGridResultColumnDisplaysInfo.STGridResultColumnWidth = GridColumn.Width;
                        objSTGridResultColumnDisplaysInfo.STModuleID = new STModulesController().GetObjectIDByName(Name);
                        objSTGridResultColumnDisplaysInfo.STGridResultSortOrder = GridColumn.VisibleIndex;
                        objSTGridResultColumnDisplaysController.CreateObject(objSTGridResultColumnDisplaysInfo);

                    }
                }
                MessageBox.Show("Save successfully.", "#Cảnh báo#", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary type="Customize">
        /// Customize Column on Search Results Control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="SearchResultsControlName" type="String"></THSparam>
        public void CustomizeColumnSearchResultsControl(object sender, String strEventName)
        {
            String strSearchResultsControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                sender, strEventName,
                                                "CustomizeColumnSearchResultsControl",
                                                "SearchResultsControlName");
            if (Controls[strSearchResultsControlName] != null)
            {
                ShowColumnSelector(((DevExpress.XtraGrid.GridControl)Controls[strSearchResultsControlName]), true);
            }
        }

        /// <summary>
        /// Customize Column grid Control
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="GridControlName" type="String"></THSparam>
        public void CustomizeColumnGridControl(object sender, String strEventName)
        {
            String strGridControl = GetTHSParameterValueFromFunctionNameAndParameterName(
                                    sender, strEventName,
                                    "CustomizeColumnGridControl",
                                    "GridControlName");
            if (Controls[strGridControl] != null)
                ShowColumnSelector(((DevExpress.XtraGrid.GridControl)Controls[strGridControl]), true);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="GridControlName" type="String"></THSparam>
        public void SaveCustomizeColumnGridControl(object sender, String strEventName)
        {
            String strGridControl = GetTHSParameterValueFromFunctionNameAndParameterName(
                                                sender, strEventName,
                                                "SaveCustomizeColumnGridControl",
                                                "GridControlName");
            Control gridControl = Controls[strGridControl];
            if (gridControl != null)
            {
                STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                                        ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                        gridControl.Name);
                if (objSTFieldsInfo != null)
                {
                    STFieldColumnsController objSTFieldColumnsController = new STFieldColumnsController();
                    objSTFieldColumnsController.DeleteByForeignColumn("STFieldID", objSTFieldsInfo.STFieldID);

                    foreach (DevExpress.XtraGrid.Columns.GridColumn GridColumn in ((DevExpress.XtraGrid.Views.Grid.GridView)((DevExpress.XtraGrid.GridControl)gridControl).ViewCollection[0]).Columns)
                    {
                        if (GridColumn.Visible)
                        {
                            STFieldColumnsInfo objSTFieldColumnsInfo = new STFieldColumnsInfo();
                            objSTFieldColumnsInfo.STFieldID = objSTFieldsInfo.STFieldID;
                            objSTFieldColumnsInfo.STFieldColumnFieldName = GridColumn.FieldName;
                            objSTFieldColumnsInfo.STFieldColumnName = GridColumn.Name;
                            objSTFieldColumnsInfo.STFieldColumnCaption = GridColumn.Caption;
                            objSTFieldColumnsInfo.STFieldColumnWidth = GridColumn.Width;
                            objSTFieldColumnsInfo.STFieldColumnVisibleIndex = GridColumn.VisibleIndex;

                            objSTFieldColumnsController.CreateObject(objSTFieldColumnsInfo);

                        }
                    }
                    MessageBox.Show("Save successfully.", "#Cảnh báo#", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
#endif
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="strEventName"></param>
        /// <THSparam name="NextControlName" type="String"></THSparam>
        public void MoveNextControlOnEnter(object sender, String strEventName)
        {
            String strNextControlName = GetTHSParameterValueFromFunctionNameAndParameterName(
                                        sender, strEventName,
                                        "MoveNextControlOnEnter", "NextControlName");
            Controls[strNextControlName].Focus();
            if (Controls[strNextControlName] is DevExpress.XtraEditors.TextEdit)
                ((DevExpress.XtraEditors.TextEdit)Controls[strNextControlName]).SelectAll();
            else if (Controls[strNextControlName] is ComboBox)
                ((ComboBox)Controls[strNextControlName]).SelectAll();
        }

        protected void InvokeAllMethodsForControlEvent(object sender, String strEventName)
        {
            Control ctrl = sender as Control;

            STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                                        ModuleID,
                                                                        THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                        ctrl.Name);
            if (objSTFieldsInfo != null)
            {
                //Get Field Event
                STFieldEventsInfo objSTFieldEventsInfo = new STFieldEventsController().GetFieldEventByFieldIDAndEventName(objSTFieldsInfo.STFieldID, strEventName);

                if (objSTFieldEventsInfo != null)
                {
                    //Get all Functions implement field event
                    DataSet dsFieldEventFunctions = new STFieldEventFunctionsController().GetFieldEventFunctionByFieldEventID(objSTFieldEventsInfo.STFieldEventID);
                    if (dsFieldEventFunctions.Tables.Count > 0)
                    {
                        foreach (DataRow rowFieldEventFunction in dsFieldEventFunctions.Tables[0].Rows)
                        {
                            STFieldEventFunctionsInfo objSTFieldEventFunctionsInfo = (STFieldEventFunctionsInfo)new STFieldEventFunctionsController().GetObjectFromDataRow(rowFieldEventFunction);

                            MethodInfo method = GetMethodInfoByMethodFullNameAndMethodClass(objSTFieldEventFunctionsInfo.STFieldEventFunctionName,
                                                                                            objSTFieldEventFunctionsInfo.STFieldEventFunctionFullName,
                                                                                            objSTFieldEventFunctionsInfo.STFieldEventFunctionClass);
                            if (method != null)
                                //Invoke method                                
                                method.Invoke(this, GetMethodParameterValues(method.GetParameters(), sender, strEventName));
                        }
                    }
                    dsFieldEventFunctions.Dispose();
                }
            }

        }

        /// <summary>
        /// Control Click Function
        /// </summary>
        /// <param name="sender">object send the click event</param>
        /// <param name="e">Event Arguments</param>
        public void Control_Click(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "Click");
        }


        public void Control_MouseUp(object sender, MouseEventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "MouseUp");
        }

        public void Control_TextChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "TextChanged");

        }


        public void Control_Validated(object sender, EventArgs e)
        {
            bool isContinue = true;
           
            Control ctrl = sender as Control;
            if (ctrl is DevExpress.XtraEditors.TextEdit && ctrl.Tag.Equals("DC"))
            {
                if (!Toolbar.IsNullOrNoneAction())
                {
                    STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName
                                                                            (ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                             ctrl.Name);
                    if (objSTFieldsInfo != null)
                    {
                        String strTableName = objSTFieldsInfo.STFieldDataSource;
                        String strColumnName = objSTFieldsInfo.STFieldDataMember;
                        if (THSDbUtil.IsForeignKey(strTableName, strColumnName))
                        {
                            int id = Convert.ToInt32((ctrl as DevExpress.XtraEditors.TextEdit).EditValue);
                            if (id > 0)
                            {
                                String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(strTableName, strColumnName);
                                BaseBusinessController objBusinessController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                                if (!objBusinessController.IsExist(id))
                                {
                                    MessageBox.Show("Nhập không chính xác", "#Cảnh báo#", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                    isContinue = false;
                                }
                            }
                        }
                    }
                }
                else
                {
                    isContinue = ctrl.Enabled;
                }
            }

            if (isContinue)
                InvokeAllMethodsForControlEvent(sender, "Validated");
            else
            {
                if (ctrl.Enabled)
                {
                    ctrl.Focus();
                    (ctrl as DevExpress.XtraEditors.TextEdit).EditValue = 0;
                    (ctrl as DevExpress.XtraEditors.TextEdit).SendKeyUp(new KeyEventArgs(Keys.F2));
                }
            }
        }


        public virtual void Control_EditValueChanged(object sender, EventArgs e)
        {
            Control ctrl = (Control)sender;
            if (ctrl is DevExpress.XtraEditors.TextEdit)
            {
               
                STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldBySTModuleIDAndSTUserGroupIDAndSTFieldName(
                                                                            ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                                            ctrl.Name);
                if (objSTFieldsInfo != null)
                {
                    if (THSDbUtil.IsForeignKey(objSTFieldsInfo.STFieldDataSource, objSTFieldsInfo.STFieldDataMember))
                    {
                        int id = Convert.ToInt32((ctrl as DevExpress.XtraEditors.TextEdit).EditValue);
                        String strLabelName = "fld_lbl" + ctrl.Name.Substring(7);
                        if (Controls[strLabelName] != null)
                        {
                            String strLookupTable = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(objSTFieldsInfo.STFieldDataSource, objSTFieldsInfo.STFieldDataMember);
                            BaseBusinessController objBusinessController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                            String strName = objBusinessController.GetObjectNameByID(id);
                            Controls[strLabelName].Text = strName;
                        }
                    }
                }
            }
        }



        public void Control_Enter(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "Enter");
        }

        public void Control_Leave(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "Leave");

        }

        public virtual void Control_KeyDown(object sender, KeyEventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "KeyDown");
        }

        public virtual void Control_KeyUp(object sender, KeyEventArgs e)
        {
            BaseActionForControlKeyUp(sender as Control, e);
            InvokeAllMethodsForControlEvent(sender, "KeyUp");
        }

        protected void BaseActionForControlKeyUp(Control ctrl, KeyEventArgs e)
        {
            THSERPScreen scr = null;
            try
            {
                scr = (THSERPScreen)((Control)ctrl.FindForm());
            }
            catch (Exception ex)
            {
                return;
            }
            STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldByFieldNameAndScreenIDAndUserGroupID(
                                                                                ctrl.Name,
                                                                                scr.ScreenID,
                                                                                THSApp.CurrentUserGroupInfo.ADUserGroupID);



            if (e.KeyCode == Keys.F2)
            {
               
                if (THSDbUtil.IsForeignKey(objSTFieldsInfo.STFieldDataSource, objSTFieldsInfo.STFieldDataMember))
                {
                    String strPrimaryTableName = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(objSTFieldsInfo.STFieldDataSource, objSTFieldsInfo.STFieldDataMember);
                    guiSearch _guiSearch = new guiSearch(this, strPrimaryTableName, ctrl.Name, ctrl.Text);
                    _guiSearch.ShowDialog();
                }
                else if ((objSTFieldsInfo.STFieldTag == THSScreen.SearchControl) && !String.IsNullOrEmpty(objSTFieldsInfo.STFieldGroup))
                {
                    String strPrimaryTableName = objSTFieldsInfo.STFieldGroup;
                    guiSearch _guiSearch = new guiSearch(this, strPrimaryTableName, ctrl.Name, ctrl.Text);
                    _guiSearch.ShowDialog();
                }
            }
           
            else if (e.KeyCode == Keys.Enter)
            {
                String strFieldTabStopsGroupName = new STFieldTabStopsController().GetFieldTabStopsGroupNameByModuleNameAndFieldName(this.Name, objSTFieldsInfo.STFieldName);
                if (objSTFieldsInfo.STFieldTag == "DC")
                {
                    //MoveNextErrorControl(ctrl);
                }
                else if (objSTFieldsInfo.STFieldTag == "SC")
                {
                    Search();
                }
                MoveNextControlInFieldTabStopsGroup(strFieldTabStopsGroupName, objSTFieldsInfo.STFieldName);
            }

           
            if (e.KeyCode == Keys.NumLock || e.KeyCode == Keys.CapsLock || e.KeyCode == Keys.Scroll)
            {

                this.ParentScreen.CheckKeyBoard(e);
            }
        }


        public virtual void LookupEdit_PropertiesChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "PropertiesChanged");
        }

        public virtual void LookupEdit_EditValueChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "EditValueChanged");
        }

        public virtual void CheckEdit_CheckedChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "CheckedChanged");
        }

        public virtual void CheckEdit_EditValueChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "EditValueChanged");
        }

        public virtual void TextEdit_EditValueChanged(object sender, EventArgs e)
        {
            InvokeAllMethodsForControlEvent(sender, "EditValueChanged");

        }
        /// <summary>
        /// Toolbar Button Item Click function
        /// </summary>
        /// <param name="sender">object send Item Click event</param>
        /// <param name="e">Item Click Event Arguments</param>
        public void ScreenToolbarButton_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.XtraBars.BarLargeButtonItem toolbarButton = (DevExpress.XtraBars.BarLargeButtonItem)e.Item;

            int iScreenID = new STScreensController().GetScreenIDByModuleIDAndUserGroupIDAndScreenName(
                                                        ModuleID, THSApp.CurrentUserGroupInfo.ADUserGroupID,
                                                        toolbarButton.Manager.Form.Name);
            if (iScreenID > 0)
            {
                THSLib.STFieldsInfo objSTFieldsInfo = new STFieldsController().GetFieldByFieldNameAndScreenIDAndUserGroupID(toolbarButton.Name, iScreenID, THSApp.CurrentUserGroupInfo.ADUserGroupID);
                if (objSTFieldsInfo != null)
                {
                    STFieldEventsInfo objSTFieldEventsInfo = new STFieldEventsController().GetFieldEventByFieldIDAndEventName(objSTFieldsInfo.STFieldID, "ItemClick");
                    if (objSTFieldEventsInfo != null)
                    {
                        DataSet dsFieldEventFunctions = new STFieldEventFunctionsController().GetFieldEventFunctionByFieldEventID(objSTFieldEventsInfo.STFieldEventID);
                        if (dsFieldEventFunctions.Tables.Count > 0)
                        {
                            foreach (DataRow rowFieldEventFunction in dsFieldEventFunctions.Tables[0].Rows)
                            {
                                STFieldEventFunctionsInfo objSTFieldEventFunctionsInfo = (STFieldEventFunctionsInfo)new STFieldEventFunctionsController().GetObjectFromDataRow(rowFieldEventFunction);

                                MethodInfo method = GetMethodInfoByMethodFullNameAndMethodClass(objSTFieldEventFunctionsInfo.STFieldEventFunctionName,
                                                                                                objSTFieldEventFunctionsInfo.STFieldEventFunctionFullName,
                                                                                                objSTFieldEventFunctionsInfo.STFieldEventFunctionClass);
                                method.Invoke(this, GetMethodParameterValues(method.GetParameters(), sender, "ItemClick"));
                            }
                        }
                        dsFieldEventFunctions.Dispose();
                    }
                }
            }
        }


       //Show contact type screen
        public virtual void ShowContactTypeScreen(object sender, EventArgs e)
        {
            guiContactType guiContactType = new guiContactType();
            guiContactType.Module = this;
            guiContactType.ShowDialog();
        }


        #region Event for Product Validated, Product Qty Validated, Product unit Price Validated

        public virtual void THSProductLookupEdit_Validated(object sender, EventArgs e)
        {
            
            
            THSLookupEdit lkeProduct = (THSLookupEdit)sender;
            if (lkeProduct == null)
                return;
            //Comment these rows
            //if (lkeProduct.OldEditValue == lkeProduct.EditValue)
            //    return;

            String strItemTableName = lkeProduct.THSDataSource;
            int iICProductID = Convert.ToInt32(lkeProduct.EditValue);
            if (iICProductID > 0 && !String.IsNullOrEmpty(strItemTableName))
            {
                CurrentModuleEntity.SetValuesAfterValidateProduct(iICProductID);
                if (_uiInventoryInformation != null)
                {
                    CalculateTotalProductQuantityForAllStock();
                    CalculateProductQuantityForProductStock();
                }
            }
        }

        public virtual void ProductQtyTextEdit_Validated(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit txtProductQty = (DevExpress.XtraEditors.TextEdit)sender;
            if (txtProductQty == null)
                return;
            if (txtProductQty.OldEditValue == txtProductQty.EditValue)
                return;

            CurrentModuleEntity.SetValuesAfterValidateProductQty();
        }

        public virtual void ProductUnitPriceTextEdit_Validated(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit txtProductUnitPrice = (DevExpress.XtraEditors.TextEdit)sender;
            if (txtProductUnitPrice == null)
                return;
            if (txtProductUnitPrice.OldEditValue == txtProductUnitPrice.EditValue)
                return;

            CurrentModuleEntity.SetValuesAfterValidateProductUnitPrice();
        }
        #endregion
        #endregion

        //Event for validating employee
        public void THSLookupEditEmployee_Validated(object sender, EventArgs e)
        {
            THSLookupEdit lke = (THSLookupEdit)sender;
            if (lke != null)
            {
                int iEmployeeID = Convert.ToInt32(lke.EditValue);
                if (iEmployeeID > 0)
                {
                    String strTableName = lke.THSDataSource;
                    CurrentModuleEntity.SetDefaultValuesFromEmployee(iEmployeeID, strTableName);
                }
            }
        }

        //Move next control in field tab stops group
        public virtual void MoveNextControlInFieldTabStopsGroup(String strGroupName, String strFieldName)
        {
            STFieldTabStopsController objFieldTabStopsController = new STFieldTabStopsController();
            List<STFieldTabStopsInfo> lstFieldTabStopsGroup = objFieldTabStopsController.GetFieldTabStopsGroupByModuleNameAndGroupName(this.Name, strGroupName);

            foreach (STFieldTabStopsInfo objFieldTabStopsInfo in lstFieldTabStopsGroup)
                if (objFieldTabStopsInfo.STFieldName == strFieldName)
                {
                    String strNextControlName;
                    if (objFieldTabStopsInfo.STFieldTabStopAction == "END")
                        strNextControlName = GetNextControlNameByFieldTabStopAction(lstFieldTabStopsGroup, "BEGIN");
                    else
                        strNextControlName = GetNextControlNameByFieldTabStopSortOrder(lstFieldTabStopsGroup, objFieldTabStopsInfo.STFieldTabStopSortOrder + 1);
                    if (Controls[strNextControlName] != null)
                    {
                        Controls[strNextControlName].Focus();
                        (Controls[strNextControlName] as DevExpress.XtraEditors.BaseEdit).SelectAll();
                    }
                    return;
                }
        }

        
        public String GetNextControlNameByFieldTabStopAction(List<STFieldTabStopsInfo> lstFieldTabStopsGroup, String strFieldTabStopAction)
        {
            foreach (STFieldTabStopsInfo objFieldTabStopsInfo in lstFieldTabStopsGroup)
                if (objFieldTabStopsInfo.STFieldTabStopAction == strFieldTabStopAction)
                    return objFieldTabStopsInfo.STFieldName;
            return String.Empty;
        }

        
        public String GetNextControlNameByFieldTabStopSortOrder(List<STFieldTabStopsInfo> lstFieldTabStopsGroup, int iSortOrder)
        {
            foreach (STFieldTabStopsInfo objFieldTabStopsInfo in lstFieldTabStopsGroup)
                if (objFieldTabStopsInfo.STFieldTabStopSortOrder == iSortOrder)
                    return objFieldTabStopsInfo.STFieldName;
            return String.Empty;
        }
    }
}
